from flask import Flask, request, jsonify
from flask_cors import CORS
import os
import json
import time
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope

app = Flask(__name__)
CORS(app)  # 启用CORS支持

# 设置DashScope API基础URL
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

@app.route('/api/aliyun/video-generation', methods=['POST'])
def generate_video():
    try:
        data = request.json
        api_token = data.get('apiToken')
        model = data.get('model', 'wanx-v1')
        prompt = data.get('prompt')
        style = data.get('style', '<auto>')
        size = data.get('size', '1280*720')
        fps = data.get('fps', 24)
        duration = data.get('duration', 10)
        
        if not api_token:
            return jsonify({"error": "API token is required"}), 400
        
        # 设置API密钥
        dashscope.api_key = api_token
        
        # 获取图片URL（如果有）
        img_url = None
        if 'photos' in data and data['photos'] and len(data['photos']) > 0:
            img_url = data['photos'][0].get('url')
            # 验证URL格式
            if img_url and not (img_url.startswith('http://') or img_url.startswith('https://')):
                print(f"无效的图片URL格式: {img_url}")
                img_url = None
        
        # 根据是否有图片选择不同的模型和参数
        if img_url:
            # 图片转视频
            print(f"使用图片生成视频: {img_url}")
            try:
                rsp = VideoSynthesis.async_call(
                    model='wan2.5-i2v-preview',
                    prompt=prompt,
                    img_url=img_url
                )
            except Exception as e:
                print(f"图片转视频API调用失败: {str(e)}")
                # 如果图片URL无效，尝试使用文本生成视频
                print("尝试使用文本生成视频")
                rsp = VideoSynthesis.async_call(
                    model=model,
                    prompt=prompt
                )
        else:
            # 文本生成视频
            print("使用文本生成视频")
            rsp = VideoSynthesis.async_call(
                model=model,
                prompt=prompt
            )
        
        print(f"API响应: {rsp}")
        
        if rsp.status_code == HTTPStatus.OK:
            return jsonify({
                "output": {
                    "task_id": rsp.output.task_id
                },
                "request_id": rsp.request_id
            })
        else:
            print(f'API调用失败, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
            return jsonify({
                "error": rsp.message,
                "code": rsp.code,
                "status_code": rsp.status_code
            }), rsp.status_code
            
    except Exception as e:
        print(f"生成视频时出错: {str(e)}")
        return jsonify({"error": f"Failed to generate video: {str(e)}"}), 500

@app.route('/api/aliyun/task-status/<task_id>', methods=['GET'])
def get_task_status(task_id):
    try:
        api_token = request.args.get('apiToken')
        
        if not api_token:
            return jsonify({"error": "API token is required"}), 400
        
        # 设置API密钥
        dashscope.api_key = api_token
        
        # 创建一个简单的响应对象用于fetch
        class TaskResponse:
            def __init__(self, task_id):
                self.task_id = task_id
        
        task_response = TaskResponse(task_id)
        
        # 获取任务状态
        status = VideoSynthesis.fetch(task_response)
        print(f"任务状态查询结果: {status}")
        
        if status.status_code == HTTPStatus.OK:
            return jsonify({
                "output": {
                    "task_id": task_id,
                    "task_status": status.output.task_status
                },
                "request_id": status.request_id
            })
        else:
            print(f'查询任务状态失败, status_code: {status.status_code}, code: {status.code}, message: {status.message}')
            return jsonify({
                "error": status.message,
                "code": status.code,
                "status_code": status.status_code
            }), status.status_code
            
    except Exception as e:
        print(f"查询任务状态时出错: {str(e)}")
        return jsonify({"error": f"Failed to check task status: {str(e)}"}), 500

@app.route('/api/aliyun/task-result/<task_id>', methods=['GET'])
def get_task_result(task_id):
    try:
        api_token = request.args.get('apiToken')
        
        if not api_token:
            return jsonify({"error": "API token is required"}), 400
        
        # 设置API密钥
        dashscope.api_key = api_token
        
        # 创建一个简单的响应对象用于wait
        class TaskResponse:
            def __init__(self, task_id):
                self.task_id = task_id
        
        task_response = TaskResponse(task_id)
        
        # 等待任务完成
        rsp = VideoSynthesis.wait(task_response)
        print(f"任务完成结果: {rsp}")
        
        if rsp.status_code == HTTPStatus.OK:
            return jsonify({
                "output": {
                    "task_id": task_id,
                    "task_status": "SUCCEEDED",
                    "results": [{"url": rsp.output.video_url}]
                },
                "request_id": rsp.request_id
            })
        else:
            print(f'获取任务结果失败, status_code: {rsp.status_code}, code: {rsp.code}, message: {rsp.message}')
            return jsonify({
                "error": rsp.message,
                "code": rsp.code,
                "status_code": rsp.status_code
            }), rsp.status_code
            
    except Exception as e:
        print(f"获取任务结果时出错: {str(e)}")
        return jsonify({"error": f"Failed to get task result: {str(e)}"}), 500

@app.route('/api/simulate-video-generation', methods=['POST'])
def simulate_video_generation():
    try:
        data = request.json
        photos = data.get('photos', [])
        options = data.get('options', {})
        
        # 模拟处理时间
        time.sleep(2)
        
        # 生成模拟视频结果
        video_id = f"video_{int(time.time())}"
        result = {
            "success": True,
            "taskId": video_id,
            "videoUrl": "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
            "thumbnail": photos[0].get('thumbnail') if photos else "https://picsum.photos/seed/video/300/200.jpg",
            "duration": options.get('duration', 10),
            "size": f"{int(10 + (len(photos) * 2))}MB",
            "createdAt": time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
        }
        
        return jsonify(result)
        
    except Exception as e:
        print(f"模拟生成时出错: {str(e)}")
        return jsonify({"error": f"Simulation failed: {str(e)}"}), 500

@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({"status": "healthy", "message": "Python backend server is running"})

if __name__ == '__main__':
    print("正在启动Python后端服务器...")
    print("服务器将在 http://localhost:3002 上运行")
    print("按 Ctrl+C 停止服务器")
    app.run(host='0.0.0.0', port=3002, debug=True)